<template>
	<div class="bg-white m-4 mr-0 overflow-hidden">
		<BasicTree
			title="数据源"
			:load-data="onLoadData"
			toolbar
			ref="asyncTreeRef"
			search
			:clickRowToExpand="false"
			:treeData="treeData"
			:fieldNames="{ label: 'name', key: 'id' }"
			@select="handleSelect"
		/>
	</div>
</template>
<script lang="ts" setup>
import { onMounted, ref, unref } from 'vue';

import { BasicTree, TreeActionType, TreeItem } from '/@/components/Tree';
import { allList, schemaList } from '/@/api/system/datasource';
const emit = defineEmits(['select']);

const treeData = ref<TreeItem[]>([]);
const asyncTreeRef = ref<Nullable<TreeActionType>>(null);

async function fetch() {
	treeData.value = ((await allList()) as unknown) as TreeItem[];
}

function onLoadData(treeNode) {
	return new Promise((resolve: (value?: unknown) => void) => {
		if (!treeNode.children) {
			resolve();
			return;
		}
		const asyncTreeAction: TreeActionType | null = unref(asyncTreeRef);
		schemaList({ id: treeNode.eventKey }).then(res => {
			if (asyncTreeAction && res.length > 0) {
				const nodeChildren = res.map((schema, index) => {
					return {
						name: schema.name,
						id: schema.name,
						parentId: treeNode.eventKey,
						isLeaf: true
					};
				});
				asyncTreeAction.updateNodeByKey(treeNode.eventKey, { children: nodeChildren });
				asyncTreeAction.setExpandedKeys([treeNode.eventKey, ...asyncTreeAction.getExpandedKeys()]);
			}
			resolve();
			return;
		});
	});
}

function handleSelect(keys: string, e) {
	const selectNode = e.selectedNodes[0];
	if (selectNode) {
		const { props } = selectNode;
		if (props.isLeaf) {
			emit('select', {
				id: props.parentId,
				schema: props.name
			});
		}
	}
}

onMounted(() => {
	fetch();
});
</script>
